<template>
  <div>
    <el-form
      :model="inputForm"
      size="small"
      ref="inputForm"
      v-loading="loading"
      :class="method === 'view' ? 'readonly' : ''"
      :disabled="method === 'view'"
      label-width="120px"
    >
      <el-row :gutter="15">
        <div class="line-bottom">活动配置</div>
        <el-col :span="24">
          <el-form-item
            label="活动名称:"
            prop="activeName"
            :rules="[
              {
                required: true,
                message: '活动名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="inputForm.activeName"
              placeholder="请填写活动名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="通道名称:"
            prop="aisleCode"
            :rules="[
              {
                required: true,
                message: '通道名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.aisleCode"
              placeholder="请选择通道名称"
              clearable
              @change="changeAisle"
            >
              <el-option
                v-for="item in aisleCodeList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="通道商名称:"
            prop="agentAisleCode"
            :rules="[
              {
                required: true,
                message: '通道商名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.agentAisleCode"
              placeholder="请选择通道商名称"
            >
              <el-option
                v-for="item in agentAisleCodeList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="通道简称:"
            prop="aisleKind"
            :rules="[
              {
                required: true,
                message: '通道简称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.aisleKind"
              placeholder="请选择通道简称"
            >
              <el-option
                v-for="item in aisleKindList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="银行名称:"
            prop="bankCode"
            :rules="[
              {
                required: true,
                message: '银行名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.bankCode"
              placeholder="请选择银行名称"
            >
              <el-option
                v-for="item in bankCodeList"
                :key="item.bankCode"
                :label="item.bankName"
                :value="item.bankCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item
            prop="timeDate"
            label="有效期"
            :rules="[
              {
                required: true,
                message: '有效期不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-date-picker
              v-model="inputForm.timeDate"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="timeDateChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-image-viewer
        style="z-index: 99999"
        v-if="imgShow"
        :on-close="
          () => {
            imgShow = false;
          }
        "
        :url-list="imgUrlList"
      ></el-image-viewer>
      <avue-crud
        :option="option"
        :search.sync="search"
        :table-loading="loading"
        :data="inputForm.subList"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @sort-change="sortChange"
        @on-load="onLoad"
      >
        <template slot-scope="{ row }" slot="regionList">
          <el-button
            size="small"
            @click.stop="handleRegion(row, index)"
            >配置范围</el-button
          >
        </template>
        <template slot-scope="{ row }" slot="regionListForm">
          <el-button
            size="small"
            @click.stop="handleRegion(row, index)"
            >配置范围</el-button
          >
        </template>
      </avue-crud>
      <el-row :gutter="15">
        <div class="line-bottom m-tt">活动状态</div>
        <el-col :span="24">
          <el-form-item label="联合活动状态:" prop="isEnable">
            <el-radio-group v-model="inputForm.isEnable">
              <el-radio :label="1">正常生效</el-radio>
              <el-radio :label="0">暂停新增</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <div style="margin-top: 30px" class="line-bottom">活动详情</div>
        <el-col :span="24">
          <el-form-item label-width="0" prop="content">
            <avue-ueditor
              v-model="inputForm.content"
              :options="ueditorOptions"
            ></avue-ueditor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog title="地区配置"
               append-to-body
               :visible.sync="dialogMenuVisible"
               width="450px">
        <div class="region-div">
          <haruyukiRegionGrant ref="toRegionGrant" />
        </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogMenuVisible = false">取 消</el-button>
        <el-button size="small" type="primary" v-preventClick @click="regionSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRegion } from "@/api/system/dict";
import { getDictionary } from "@/api/system/dict";
import { bankPage } from "@/api/rb-oem/uniteOrder/unite_order";
import haruyukiRegionGrant from "@/components/module/haruyuki-region-grant";

export default {
  props: {
    inputForm: {
      type: Object,
      default: () => {
        return {
          activeCode: "",
          aisleKind: "",
          bankCode: "",
          activeName: "",
          aisleCode: "",
          isEnable: 1,
          subList: [
            {
                regionList: [],
                subBankName: '',
                subBankCode: '',
                activityId: '',
                subsidy: '',
                restitutionType: '',
                isEnable: '',
                $cellEdit: true
            }
          ],
          beginDate: "",
          endDate: "",
          content: "",
          timeDate: [],
        };
      },
    },
    method: {
      type: String,
      default: "",
    },
  },
  components: {
    haruyukiRegionGrant,
  },
  data() {
    return {
      screenWidth: document.documentElement.clientWidth,
      imgShow: false,
      imgUrlList: [],
      loading: false,
      aisleCodeList: [],
      agentAisleCodeList: [],
      aisleKindList: [],
      bankCodeList: [],
      isShow: true,
      dialogMenuVisible: false,
      regionData: {},
      data: [],
      search: {},
      form: {},
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        allPrice: 0,
      },
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      option: {
        //height: "auto",
        calcHeight: 30,
        border: true,
        index: true,
        addBtn: false,
        editBtn: false,
        addRowBtn: true,
        cellBtn: true,
        saveBtn: false,
        cancelBtnText: '删除',
        menuWidth: 160,
        column: [
          {
            label: "省份/地市/区县",
            labelWidth: 130,
            prop: "regionList",
            slot: true,
            width: 110,
            cell: true,
            rules: [
              {
                required: true,
                message: "请选择省份/地市/区县",
                trigger: "blur",
              },
            ],
          },
          {
            label: "支行名称",
            prop: "subBankName",
            slot: true,
            overHidden: true,
            width: 140,
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入支行名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "支行编号",
            prop: "subBankCode",
            overHidden: true,
            width: 140,
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入支行编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "活动ID",
            prop: "activityId",
            overHidden: true,
            width: 140,
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入活动ID",
                trigger: "blur",
              },
            ],
          },
          {
            label: "补贴模式",
            prop: "subsidy",
            type: "select",
            dicUrl:
              "/api/blade-system/dict/dictionary?code=bank_active_subsidy",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            width: 120,
            cell: true,
            rules: [
              {
                required: true,
                message: "请选择补贴模式",
                trigger: "blur",
              },
            ],
          },
          {
            label: "返还对象",
            prop: "restitutionType",
            type: "select",
            dicUrl:
              "/api/blade-system/dict/dictionary?code=bank_active_restitution_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            width: 120,
            cell: true,
            rules: [
              {
                required: true,
                message: "请选择返还对象",
                trigger: "blur",
              },
            ],
          },
          {
            label: "新增状态",
            prop: "isEnable",
            type: "select",
            dicUrl:
              "/api/blade-system/dict/dictionary?code=bank_active_is_enable",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            showColumn: false,
            width: 120,
            cell: true,
            rules: [
              {
                required: true,
                message: "请选择新增状态",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      ueditorOptions: {
        //普通上传地址
        action: "/api/blade-resource/oss/endpoint/put-file",
        customConfig: {}, //wangEditor编辑的配置
        props: {
          // home: '',
          res: "data",
          url: "link",
        },
      },
      regionForm: {}
    };
  },
  watch: {
    method: {
      handler(val) {
        if (val === "view") {
          this.option.editBtn = false;
          this.option.delBtn = false;
        } else {
          this.option.editBtn = true;
          this.option.delBtn = true;
        }
      },
      immediate: true,
      // deep: true
    },
    inputForm: {
      handler(val) {
        if (val) {
          this.doGetDicts();
        }
      },
      immediate: true,
      // deep: true
    },
  },
  created() {
    // this.doGetDicts();
  },
  methods: {
    /* 字典 */
    doGetDicts() {
      getDictionary({ code: "aisle_code" }).then((res) => {
        this.aisleCodeList = res.data.data;
      });
      getDictionary({ code: "agent_aisle_code" }).then((res) => {
        this.agentAisleCodeList = res.data.data;
      });
      getDictionary({ code: "aisle_kind" }).then((res) => {
        this.aisleKindList = res.data.data;
      });

      this.$nextTick(() => {
        if (this.inputForm.aisleCode) {
          bankPage("-1", "-1", Object.assign(this.query, { aisleCode: this.inputForm.aisleCode })).then(
            (res) => {
              this.bankCodeList = res.data.data.records;
            }
          );
        }
        // if (this.inputForm.beginDate && this.inputForm.endDate) {
        //   this.$set(this.inputForm, "timeDate", [
        //     this.inputForm.beginDate,
        //     this.inputForm.endDate,
        //   ]);
        // }
        this.$forceUpdate();
      });
    },
    changeAisle(e) {
      if (e) {
        bankPage("-1", "-1", Object.assign(this.query, { aisleCode: e })).then(
          (res) => {
            this.bankCodeList = res.data.data.records;
          }
        );
      }
    },
    timeDateChange(e) {
      this.inputForm.beginDate = e[0];
      this.inputForm.endDate = e[1];
    },
    handleRegion(row) {
      if (row.$cellEdit) {
        this.dialogMenuVisible = true;
        this.regionData = row;
        this.$nextTick(() => {
          this.$refs["toRegionGrant"].getMenuGrant("audit", '2', row.regionList);
        })
      }
      
    },
    regionSubmit() {
      const _this = this;
      const regionList = _this.$refs["toRegionGrant"].$refs.treeMenu.getCheckedKeys();
      _this.inputForm.subList[_this.regionData.$index].regionList = regionList;
      setTimeout(() => {
        _this.dialogMenuVisible = false;
      }, 300);
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      console.log(row, 'cccccccccccccc');

    //   this.inputForm.subList.push(row);
      setTimeout(() => {
        // done();
        // this.onLoad(this.page);
      }, 300);
    },
    rowUpdate(row, index, done, loading) {
      console.log(row, 'cascaderValue');
      this.$nextTick(() => {
        // this.inputForm.subList[index] = Object.assign(
        //   this.inputForm.subList[index],
        //   {
        //     ...row,
        //   }
        // );
      });
      setTimeout(() => {
        // done();
      }, 300);
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.inputForm.subList.splice(row.$index, 1);
        })
        .then(() => {
          this.onLoad(this.page);
        });
    },
    async lazyLoad(node, resolve) {
      let stop_level = 1;
      let level = node.level;
      let data = node.data || {};
      let code = data.code;
      let list = [];
    //   if (this.rpiNo) {
    //     await getDetail(this.rpiNo).then((res) => {
    //       const form = res.data.data;
    //       form.regionList = [form.province, form.city, form.area];
    //       this.regionForm = form;
    //       console.log(this.regionForm , 'regionForm');
    //     });
    //   }
      let callback = () => {
        resolve(
          (list || []).map((ele) => {
            return Object.assign(ele, {
              ...ele,
              leaf: level >= stop_level,
            });
          })
        );
      };
      if (level == 0) {
        getRegion(code).then(
          (res) => {
            list = res.data.data;
            callback();
          },
          (error) => {
            window.console.log(error);
          }
        );
      } else if (level == 1) {
        getRegion(code).then(
          (res) => {
            list = res.data.data;
            callback();
          },
          (error) => {
            window.console.log(error);
          }
        );
      } else {
        callback();
      }
    },
    onLoad() {
      this.loading = true;
      let total = 0;
      for (const item of this.inputForm.subList) {
        total += Number(item.price);
      }
      this.$nextTick(() => {
        this.page.allPrice = Number(total.toFixed(2));
      });
      setTimeout(() => {
        this.loading = false;
      }, 300);
    },
  },
};
</script>

<style>
.line-bottom {
  font-weight: bold;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}
.m-tt {
  margin-top: 30px;
}
.redFont {
  color: red;
}

.region-div {
  height: 50vh;
  overflow-y: auto;
  padding-bottom: 10px;
}
</style>